//
//  KLTopTabBar.m
//  Test
//
//  Created by apple on 2017/12/4.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "KLTopTabBar.h"

@interface KLTopTabBar()
@property (strong, nonatomic) NSArray<NSString *> *titles;
@property (assign, nonatomic) NSUInteger preIndex;
@end

@implementation KLTopTabBar

- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray<NSString *>*)titles {
    self = [super initWithFrame:frame];
    if (self) {
        self.titles = titles;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.preIndex = -1;
    
    NSUInteger count = self.titles.count;
    if (count == 0) {
        return;
    }
    
    CGFloat itemWidth = self.bounds.size.width / count;
    CGFloat itemHeight = self.bounds.size.height;
    
    for (NSUInteger i = 0; i < count; i++) {
        UIButton *item = [[UIButton alloc] init];
        item.frame = CGRectMake( itemWidth * i, 0, itemWidth, itemHeight);
        item.titleLabel.font = [UIFont systemFontOfSize:12.0];
        [item setTitle:_titles[i] forState:UIControlStateNormal];
        [item setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        item.tag = i;
        [item addTarget:self action:@selector(clickItemAtIndex:)  forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:item];
    }
}

- (void)clickItemAtIndex:(UIButton *)button {
    
    if (button.tag == self.preIndex) {
        return;
    } else {
        self.preIndex = button.tag;
    }
    for (UIButton *item in self.subviews) {
        if (item.tag == button.tag) {
            [item setTitleColor:UIColorFromRGB(0X29B774) forState:UIControlStateNormal];
            item.titleLabel.font = [UIFont systemFontOfSize:20.0];
        } else {
            [item setTitleColor:UIColorFromRGB(0X99A4BF) forState:UIControlStateNormal];
            item.titleLabel.font = [UIFont systemFontOfSize:14.0];
        }
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectTabItemAtIndex: )]) {
        [self.delegate selectTabItemAtIndex:button.tag];
    }
}

- (void)selectDefaultTabItem:(NSUInteger)index {
    self.preIndex = index;
    for (UIButton *item in self.subviews) {
        if (item.tag == index) {
            [item setTitleColor:UIColorFromRGB(0X29B774) forState:UIControlStateNormal];
            item.titleLabel.font = [UIFont systemFontOfSize:20.0];
        } else {
            [item setTitleColor:UIColorFromRGB(0X99A4BF) forState:UIControlStateNormal];
            item.titleLabel.font = [UIFont systemFontOfSize:14.0];
        }
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectTabItemAtIndex: )]) {
        [self.delegate selectTabItemAtIndex:index];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
